// link文件测试 
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>

int main(int argc, char *argv[]) {
    int fp;
    int ret;
    
    if (argc != 2) {
        fprintf(stderr, "Usage: %s filename\n", argv[1]);
        return -1;
    }

    // 使用opendir函数打开所指定的目录
    fp = open(argv[1], O_RDWR | O_APPEND);

    if(fp == -1) {
        perror("Failed to open file");
        return -1;
    }
    
    // link链接为硬链接
    ret = link("./showname2.c", "/home/mrzhi/Desktop/showname2Link.c");
    if (ret == -1) {
        perror("Failed to link the fine");
        return -1;
    }

    char buf[1024] = "// Hello, this is a link test! \n";
    ret = write(fp, buf, strlen(buf));
    if (ret == -1) {
        perror("Failed to write to the file");
        return -1;
    }

    // 创建一个符号链接,符号链接是包含一个文件名或目录名的文件
    // 符号链接为软连接,且使用符号链接的时候需要指定绝对路径，否则链接无法使用
    ret = symlink("/home/mrzhi/Desktop/Linus-网络编程/Unix_systems_programming/chapter5_File_system/showname2.c", "/home/mrzhi/Desktop/showname2SymLink");
    // ret = symlink("/home/mrzhi/Desktop/space", "/home/mrzhi/Desktop/spaceLink");
    if (ret == -1) {
        perror("Failed to symlink the file");
        return -1;
    }

    bzero(buf, sizeof(buf));
    strcpy(buf, "// This is a symlink \n");
    ret = write(fp, buf, strlen(buf));
    if (ret == -1) {
        perror("Failed to write to the file");
        return -1;
    }

    // note:使用完毕后一定要关闭目录
    close(fp);
    return 0;
}
// Hello, this is a link test! 
// This is a symlink 
// Hello, this is a link test! 
// This is a symlink 
// Hello, this is a link test! 
// This is a symlink 
// Hello, this is a link test! 
// This is a symlink 
// Hello, this is a link test! 
// This is a symlink 
